<template>
	<view class="lyric-page">
		<!-- 歌曲信息区域 -->
		<view class="song-info">
			<text class="song-title">{{ currentSong.name }}</text>
			<text class="singer">{{ currentSong.singer }}</text>
		</view>

		<!-- 播放进度 -->
		<view class="progress-container">
			<text class="time">{{ formatTime(currentTime) }}</text>
			<view class="progress-bar" @click="handleProgressClick">
				<view class="progress-track"></view>
				<view class="progress-played" :style="{ width: progressPercent + '%' }"></view>
				<view class="progress-thumb" :style="{ left: progressPercent + '%' }"></view>
			</view>
			<text class="time">{{ formatTime(duration) }}</text>
		</view>

		<!-- 提示信息 (拖动后显示) -->
		<view v-if="showConfirmHint" class="confirm-hint">
			点击歌词确认播放位置
		</view>

		<!-- 歌词展示区域 -->
		<view class="lyric-container">
			<!-- 上下渐变蒙版 -->
			<view class="lyric-mask top-mask"></view>
			<view class="lyric-mask bottom-mask"></view>

			<!-- 基准线 (拖动时显示) -->
			<view v-if="isDragging || showConfirmHint" class="baseline">
				<view class="baseline-line"></view>
				<view class="baseline-triangle"></view>
			</view>

			<!-- 当前播放线 (始终显示当前播放位置) -->
			<view v-if="isPlaying && (isDragging || showConfirmHint)" class="current-play-line">
				<view class="current-play-indicator"></view>
			</view>

			<!-- 歌词滚动容器 -->
			<view class="lyric-scroll" :style="{ transform: `translateY(${scrollY}px)` }" @touchstart="handleDragStart"
				@touchmove="handleDragMove" @touchend="handleDragEnd" @mousedown="handleDragStart"
				@mousemove="handleDragMove" @mouseup="handleDragEnd">

				<text v-for="(line, index) in processedLyrics" :key="index" :class="{ 
						'lyric-current': index === currentLyricIndex,
						'lyric-preview': index === previewLyricIndex && (isDragging || showConfirmHint) 
					}" class="lyric-line" @click="handleLyricClick(index)">
					{{ line.text }}
				</text>
			</view>
		</view>

		<!-- 播放控制 -->
		<view class="controls">
			<button class="control-btn" @click="togglePlay">
				{{ isPlaying ? '暂停' : '播放' }}
			</button>
		</view>
	</view>
</template>
<script setup>
	import {
		ref,
		onMounted,
		nextTick,
		onUnmounted,
		computed,
		watch
	} from 'vue';
	import axios from 'axios';

	// 歌曲数据
	const currentSong = ref({
		name: '加载中...',
		singer: '加载中...',
		lyrics: [] // 原始歌词数组，包含时间和文本
	});

	// 处理后的歌词（分离时间和文本）
	const processedLyrics = ref([]);

	// 播放状态
	const isPlaying = ref(false);
	const currentTime = ref(0); // 当前播放时间（秒）
	const duration = ref(0); // 歌曲总时长（秒）
	const progressPercent = computed(() => {
		return duration.value ? (currentTime.value / duration.value) * 100 : 0;
	});

	// 歌词滚动相关变量
	const scrollY = ref(0);
	const currentLyricIndex = ref(0); // 当前实际播放的歌词索引
	const previewLyricIndex = ref(0); // 拖动预览时的歌词索引
	const isDragging = ref(false);
	const startY = ref(0);
	const initialScrollY = ref(0);
	const animationFrameId = ref(null);
	const showConfirmHint = ref(false); // 是否显示确认提示
	const originalPlayState = ref(false); // 记录拖动开始时的播放状态
	const currentPlayLinePosition = ref(0); // 当前播放线的位置

	// 基础配置（确保与CSS一致）
	const LINE_HEIGHT = 50; // 歌词行高（含间距）
	const CONTAINER_HEIGHT = 350; // 容器高度
	const CENTER_POSITION = CONTAINER_HEIGHT / 2; // 容器中心位置

	// 格式化时间（秒 -> mm:ss）
	const formatTime = (seconds) => {
		const mins = Math.floor(seconds / 60);
		const secs = Math.floor(seconds % 60);
		return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
	};

	// 解析歌词（将时间字符串转换为秒）
	const parseLyrics = (rawLyrics) => {
		return rawLyrics.map(item => {
			// 假设歌词格式为 { time: "01:23.45", text: "歌词内容" }
			if (item.time && item.text) {
				const [minSec, ms] = item.time.split('.');
				const [min, sec] = minSec.split(':').map(Number);
				const timeInSeconds = min * 60 + sec + (ms ? parseInt(ms) / 100 : 0);
				return {
					time: timeInSeconds,
					text: item.text
				};
			}
			return {
				time: 0,
				text: item.text || ''
			};
		}).sort((a, b) => a.time - b.time); // 按时间排序
	};

	// 拖动开始
	const handleDragStart = (e) => {
		isDragging.value = true;
		// 记录原始播放状态但不暂停
		originalPlayState.value = isPlaying.value;
		// 获取触摸/鼠标起始位置
		startY.value = e.type.includes('touch') ? e.touches[0].clientY : e.clientY;
		initialScrollY.value = scrollY.value;
	};

	// 拖动过程
	const handleDragMove = (e) => {
		if (!isDragging.value) return;
		e.preventDefault();

		// 计算移动距离并更新滚动位置
		const currentY = e.type.includes('touch') ? e.touches[0].clientY : e.clientY;
		const moveDistance = currentY - startY.value;
		scrollY.value = initialScrollY.value + moveDistance;

		// 更新预览高亮歌词（不影响实际播放进度）
		updatePreviewLyricIndex();
	};

	// 拖动结束
	const handleDragEnd = () => {
		isDragging.value = false;
		// 限制滚动范围
		restrictScrollRange();
		// 显示确认提示
		showConfirmHint.value = true;
	};

	// 点击歌词行 - 确认更改播放位置
	const handleLyricClick = (index) => {
		if (index >= 0 && index < processedLyrics.value.length) {
			// 更新当前播放歌词索引
			currentLyricIndex.value = index;
			// 跳转到选中的歌词时间点
			jumpToLyricTime(index);
			// 隐藏确认提示
			showConfirmHint.value = false;
		}
	};

	// 点击进度条
	const handleProgressClick = (e) => {
		const rect = e.currentTarget.getBoundingClientRect();
		const clickPosition = e.clientX - rect.left;
		const percent = (clickPosition / rect.width) * 100;
		if (duration.value) {
			const newTime = (percent / 100) * duration.value;
			currentTime.value = newTime;
			updateCurrentLyricIndex();
			updateScrollPosition();
			showConfirmHint.value = false;
		}
	};

	// 更新预览歌词索引（拖动时使用，不影响实际播放）
	const updatePreviewLyricIndex = () => {
		// 根据滚动位置计算当前预览的歌词索引
		const index = Math.round((CENTER_POSITION - scrollY.value) / LINE_HEIGHT);
		// 确保索引在有效范围内
		previewLyricIndex.value = Math.max(0, Math.min(index, processedLyrics.value.length - 1));
	};

	// 更新当前歌词索引（根据播放时间）
	const updateCurrentLyricIndex = () => {
		if (!processedLyrics.value.length) return;

		// 找到当前时间对应的歌词索引
		for (let i = 0; i < processedLyrics.value.length; i++) {
			if (currentTime.value < processedLyrics.value[i].time) {
				currentLyricIndex.value = Math.max(0, i - 1);
				return;
			}
		}

		// 如果超出所有歌词时间，选中最后一句
		currentLyricIndex.value = processedLyrics.value.length - 1;
	};

	// 限制滚动范围
	const restrictScrollRange = () => {
		// 最大滚动位置（顶部）
		const maxScroll = CENTER_POSITION;
		// 最小滚动位置（底部）
		const minScroll = CENTER_POSITION - (processedLyrics.value.length - 1) * LINE_HEIGHT;

		// 应用限制
		scrollY.value = Math.max(minScroll, Math.min(scrollY.value, maxScroll));
	};

	// 更新滚动位置（根据当前歌词索引）
	const updateScrollPosition = () => {
		// 如果正在拖动或显示确认提示，不自动更新滚动位置
		if (isDragging.value || showConfirmHint.value) return;

		scrollY.value = CENTER_POSITION - currentLyricIndex.value * LINE_HEIGHT;
		restrictScrollRange();
	};

	// 跳转到指定歌词的时间点
	const jumpToLyricTime = (index) => {
		if (processedLyrics.value[index]) {
			currentTime.value = processedLyrics.value[index].time;
			// 更新滚动位置
			updateScrollPosition();
			// 如果原本是播放状态，确保继续播放
			if (!isPlaying.value && originalPlayState.value) {
				togglePlay();
			}
		}
	};

	// 播放/暂停切换
	const togglePlay = () => {
		isPlaying.value = !isPlaying.value;
		if (isPlaying.value) {
			startPlayback();
			showConfirmHint.value = false; // 播放时隐藏确认提示
		} else {
			stopPlayback();
		}
	};

	// 开始播放进度更新
	const startPlayback = () => {
		const updateProgress = () => {
			if (isPlaying.value) {
				currentTime.value += 0.1; // 每100ms增加0.1秒

				// 检查是否播放结束
				if (currentTime.value >= duration.value && duration.value > 0) {
					currentTime.value = 0;
					isPlaying.value = false;
				} else {
					updateCurrentLyricIndex();
					updateScrollPosition();
					animationFrameId.value = requestAnimationFrame(updateProgress);
				}
			}
		};
		animationFrameId.value = requestAnimationFrame(updateProgress);
	};

	// 停止播放进度更新
	const stopPlayback = () => {
		if (animationFrameId.value) {
			cancelAnimationFrame(animationFrameId.value);
			animationFrameId.value = null;
		}
	};

	// 监听当前播放歌词索引变化，更新当前播放线位置
	watch(currentLyricIndex, (newIndex) => {
		currentPlayLinePosition.value = newIndex * LINE_HEIGHT;
	});

	// 加载歌曲数据
	const loadSongData = async (songId = 1) => {
		try {
			// 使用模拟数据替代API请求
			const mockData = {
				code: 200,
				data: [{
					id: 1,
					name: "海阔天空",
					singer: "Beyond",
					duration: 319, // 歌曲时长（秒）
					lyrics: [{
							time: "00:00.00",
							text: "海阔天空 - Beyond"
						},
						{
							time: "00:15.30",
							text: "今天我 寒夜里看雪飘过"
						},
						{
							time: "00:22.15",
							text: "怀着冷却了的心窝漂远方"
						},
						{
							time: "00:28.90",
							text: "风雨里追赶 雾里分不清影踪"
						},
						{
							time: "00:35.70",
							text: "天空海阔你与我 可会变"
						},
						{
							time: "00:42.50",
							text: "谁没在变"
						},
						{
							time: "00:48.00",
							text: "多少次 迎着冷眼与嘲笑"
						},
						{
							time: "00:54.80",
							text: "从没有放弃过心中的理想"
						},
						{
							time: "01:01.60",
							text: "一刹那恍惚 若有所失的感觉"
						},
						{
							time: "01:08.40",
							text: "不知不觉已变淡 心里爱"
						},
						{
							time: "01:15.20",
							text: "谁明白我"
						},
						{
							time: "01:21.30",
							text: "原谅我这一生不羁放纵爱自由"
						},
						{
							time: "01:28.10",
							text: "也会怕有一天会跌倒"
						},
						{
							time: "01:34.90",
							text: "背弃了理想 谁人都可以"
						},
						{
							time: "01:41.70",
							text: "哪会怕有一天只你共我"
						},
						{
							time: "02:02.50",
							text: "今天我 寒夜里看雪飘过"
						},
						{
							time: "02:09.30",
							text: "怀着冷却了的心窝漂远方"
						},
						{
							time: "02:16.10",
							text: "风雨里追赶 雾里分不清影踪"
						},
						{
							time: "02:22.90",
							text: "天空海阔你与我 可会变"
						},
						{
							time: "02:29.70",
							text: "谁没在变"
						},
						{
							time: "02:35.20",
							text: "原谅我这一生不羁放纵爱自由"
						},
						{
							time: "02:42.00",
							text: "也会怕有一天会跌倒"
						},
						{
							time: "02:48.80",
							text: "背弃了理想 谁人都可以"
						},
						{
							time: "02:55.60",
							text: "哪会怕有一天只你共我"
						},
						{
							time: "03:16.50",
							text: "仍然自由自我 永远高唱我歌"
						},
						{
							time: "03:23.30",
							text: "走遍千里"
						},
						{
							time: "03:29.80",
							text: "原谅我这一生不羁放纵爱自由"
						},
						{
							time: "03:36.60",
							text: "也会怕有一天会跌倒"
						},
						{
							time: "03:43.40",
							text: "背弃了理想 谁人都可以"
						},
						{
							time: "03:50.20",
							text: "哪会怕有一天只你共我"
						},
						{
							time: "03:56.70",
							text: "背弃了理想 谁人都可以"
						},
						{
							time: "04:03.50",
							text: "哪会怕有一天只你共我"
						},
						{
							time: "04:10.30",
							text: "Yeah! 啦啦啦啦啦啦啦啦"
						}
					]
				}]
			};

			const response = mockData;

			if (response.code === 200) {
				const songs = response.data || [];
				let targetSong = songs.find(song => song.id === songId) || songs[0];

				if (targetSong) {
					// 更新歌曲信息
					currentSong.value.name = targetSong.name || '未知歌曲';
					currentSong.value.singer = targetSong.singer || '未知歌手';
					duration.value = targetSong.duration || 0;

					// 解析歌词
					processedLyrics.value = targetSong.lyrics && Array.isArray(targetSong.lyrics) ?
						parseLyrics(targetSong.lyrics) :
						[{
							time: 0,
							text: '暂无歌词'
						}];

					// 等待DOM更新后重置滚动位置
					nextTick(() => {
						currentLyricIndex.value = 0;
						previewLyricIndex.value = 0;
						currentTime.value = 0;
						scrollY.value = CENTER_POSITION; // 初始位置
					});
				}
			}
		} catch (error) {
			console.error('加载失败:', error);
			processedLyrics.value = [{
				time: 0,
				text: '加载歌词失败，请检查网络'
			}];
		}
	};

	// 清理函数
	onUnmounted(() => {
		stopPlayback();
	});

	// 初始化
	onMounted(() => {
		loadSongData();
	});
</script>

<style scoped>
	.lyric-page {
		display: flex;
		flex-direction: column;
		align-items: center;
		background-color: #6a11cb;
		background-image: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
		height: 100vh;
		padding: 20px 16px 0;
		box-sizing: border-box;
		color: white;
	}

	.song-info {
		text-align: center;
		margin-bottom: 20px;
		width: 100%;
	}

	.song-title {
		font-size: 22px;
		font-weight: bold;
		display: block;
		margin-bottom: 8px;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}

	.singer {
		font-size: 16px;
		color: rgba(255, 255, 255, 0.8);
	}

	.progress-container {
		width: 100%;
		display: flex;
		align-items: center;
		gap: 10px;
		margin-bottom: 10px;
	}

	.time {
		font-size: 14px;
		color: rgba(255, 255, 255, 0.7);
		width: 50px;
	}

	.progress-bar {
		flex: 1;
		height: 4px;
		background-color: rgba(255, 255, 255, 0.2);
		border-radius: 2px;
		position: relative;
		cursor: pointer;
	}

	.progress-track {
		position: absolute;
		top: 0;
		left: 0;
		height: 100%;
		width: 100%;
	}

	.progress-played {
		position: absolute;
		top: 0;
		left: 0;
		height: 100%;
		background-color: #ffffff;
		border-radius: 2px;
	}

	.progress-thumb {
		position: absolute;
		top: 50%;
		width: 14px;
		height: 14px;
		background-color: #ffffff;
		border-radius: 50%;
		transform: translate(-50%, -50%);
		box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
	}

	/* 确认提示 */
	.confirm-hint {
		color: rgba(255, 255, 255, 0.8);
		font-size: 14px;
		margin-bottom: 10px;
		padding: 5px 10px;
		background-color: rgba(255, 255, 255, 0.1);
		border-radius: 4px;
		animation: fadeIn 0.3s;
	}

	@keyframes fadeIn {
		from {
			opacity: 0;
		}

		to {
			opacity: 1;
		}
	}

	.lyric-container {
		position: relative;
		width: 100%;
		height: 350px;
		/* 与JS中CONTAINER_HEIGHT一致 */
		overflow: hidden;
		margin-bottom: 30px;
	}

	.lyric-mask {
		position: absolute;
		left: 0;
		right: 0;
		z-index: 10;
		pointer-events: none;
	}

	.top-mask {
		top: 0;
		height: 80px;
		background: linear-gradient(to bottom, #6a11cb, transparent);
	}

	.bottom-mask {
		bottom: 0;
		height: 80px;
		background: linear-gradient(to top, #6a11cb, transparent);
	}

	/* 基准线样式 - 用于预览位置 */
	.baseline {
		position: absolute;
		top: 50%;
		left: 0;
		right: 0;
		transform: translateY(-50%);
		z-index: 5;
		pointer-events: none;
	}

	.baseline-line {
		height: 2px;
		background-color: rgba(255, 255, 255, 0.5);
		width: 100%;
	}

	.baseline-triangle {
		width: 0;
		height: 0;
		border-left: 6px solid transparent;
		border-right: 6px solid transparent;
		border-top: 8px solid rgba(255, 255, 255, 0.5);
		position: absolute;
		top: 2px;
		left: 50%;
		transform: translateX(-50%);
	}

	/* 当前播放线 - 显示实际播放位置 */
	.current-play-line {
		position: absolute;
		left: 0;
		right: 0;
		z-index: 6;
		pointer-events: none;
		transform: translateY(-50%);
	}

	.current-play-indicator {
		height: 2px;
		background-color: #4CAF50;
		width: 100%;
		box-shadow: 0 0 8px rgba(76, 175, 80, 0.8);
	}

	.lyric-scroll {
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		text-align: center;
		transition: transform 0.1s ease-out;
	}

	.lyric-line {
		display: block;
		height: 50px;
		/* 与JS中LINE_HEIGHT一致 */
		line-height: 50px;
		/* 确保文字垂直居中 */
		font-size: 16px;
		color: rgba(255, 255, 255, 0.6);
		transition: all 0.3s ease;
		cursor: pointer;
	}

	.lyric-line:active {
		background-color: rgba(255, 255, 255, 0.1);
	}

	/* 当前播放歌词始终保持高亮 */
	.lyric-current {
		font-size: 18px;
		color: #ffffff;
		font-weight: bold;
		text-shadow: 0 0 5px rgba(255, 255, 255, 0.5);
	}

	/* 拖动预览时的歌词样式 - 与当前播放歌词有所区别 */
	.lyric-preview {
		font-size: 17px;
		color: rgba(255, 255, 255, 0.8);
		font-weight: 500;
	}

	.controls {
		width: 100%;
		display: flex;
		justify-content: center;
	}

	.control-btn {
		background-color: rgba(255, 255, 255, 0.2);
		color: white;
		border: none;
		padding: 10px 20px;
		border-radius: 20px;
		font-size: 16px;
		cursor: pointer;
		transition: background-color 0.3s ease;
	}

	.control-btn:hover {
		background-color: rgba(255, 255, 255, 0.3);
	}
</style>